package com.cloud.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSONObject;
import com.cloud.common.domain.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;

/**
 * Sentinel 配置规则异常拦截
 *
 * @author yzj
 */
@Configuration
public class SentinelExceptionHandler implements BlockExceptionHandler {

    /**
     * BlockException 异常接口,其子类为Sentinel五种规则异常的实现类
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String message = null;
        if (e instanceof FlowException) { // 限流异常
            message = "[限流规则]限流了";
        } else if (e instanceof DegradeException) { // 降级异常
            message = "[降级规则]降级了";
        } else if (e instanceof ParamFlowException) { // 参数限流异常
            message = "[参数规则]参数限流了";
        } else if (e instanceof SystemBlockException) { // 系统负载异常
            message = "[系统规则]负载/不满足";
        } else if (e instanceof AuthorityException) { // 授权异常
            message = "[授权规则]不通过";
        }
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        ServletOutputStream out = response.getOutputStream();
        out.write(JSONObject.toJSONString(Result.error(message)).getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }

}
